import datetime
import wsgiref.handlers

import statsdb
import statsdt
import statsfmt

from google.appengine.ext import webapp
from google.appengine.ext import db

class QueryBase(webapp.RequestHandler):
  def get(self):
    data = self.getData()
    
    output = "html"
    if len(self.request.get("output")) > 0:
      output = self.request.get("output")
    if "html" == output:
      fmt = self.getHTMLFormatter()
    elif "json" == output:
      fmt = self.getJSONFormatter()
    
    fmt.respond(self, data);
        
class QueryRecord(QueryBase):
  def getData(self):
    tags = self.request.get("tags").split(" ")
    if 0 == len(self.request.get("begin")):
      begin = datetime.datetime.strptime("197001010000", "%Y%m%d%H%M%S")
    else:
      begin = datetime.datetime.strptime(self.request.get("begin"), "%Y%m%d%H%M%S")
    if 0 == len(self.request.get("end")):
      end = datetime.datetime.strptime("207001010000", "%Y%m%d%H%M%S")
    else:
      end = datetime.datetime.strptime(self.request.get("end"), "%Y%m%d%H%M%S")
      
    return statsdb.QueryRecordsByTag(begin, end, tags)
  
  def getJSONFormatter(self):
    return statsfmt.RecordJSONFormatter()

  def getHTMLFormatter(self):
    return statsfmt.RecordHTMLFormatter()
  
class QueryNextTag(QueryBase):
  def getData(self):
    bookmark = statsdb.GetTag(self.request.get("tag"))[1]
    pagesize = 10
    if True == self.request.get("pagesize").isdigit():
      pagesize = int(self.request.get("pagesize"));
    tags, bookmark, prev = statsdb.GetNextTags(bookmark, self.request.get("prevtag"), pagesize)
    
    return (tags, bookmark, prev)
  
  def getJSONFormatter(self):
    return statsfmt.NextTagJSONFormatter()    

  def getHTMLFormatter(self):
    return statsfmt.NextTagHTMLFormatter()

class QueryRelatedTag(QueryBase):
  def getData(self):
    pagesize = 10
    if True == self.request.get("pagesize").isdigit():
      pagesize = int(self.request.get("pagesize"));
    tags, bookmark = statsdb.GetRelatedTags(self.request.get("tag"), pagesize)
    
    return tags
  
  def getJSONFormatter(self):
    return statsfmt.RelatedTagJSONFormatter()    

  def getHTMLFormatter(self):
    return statsfmt.RelatedTagHTMLFormatter()

class QueryHistory(QueryBase):
  def getData(self):
    found = True
    if "false" == self.request.get("found"):
      found = False
    
    results = statsdb.History.gql("WHERE found = :1 ORDER BY qcount ASC", found)
    return results.fetch(20)

  def getJSONFormatter(self):
    return statsfmt.HistoryJSONFormatter()    

  def getHTMLFormatter(self):
    return statsfmt.HistoryHTMLFormatter()

class QueryTagIndex(QueryBase):
  def getData(self):
    return statsdb.QueryTagIndexByWords(self.request.get("words"))

  def getJSONFormatter(self):
    return statsfmt.TagIndexJSONFormatter()

  def getHTMLFormatter(self):
    return statsfmt.TagIndexHTMLFormatter()

def main():
  application = webapp.WSGIApplication([("/queryrecord", QueryRecord),
                                        ("/querynexttag", QueryNextTag),
                                        ("/queryrelatedtag", QueryRelatedTag),
                                        ("/querytagindex", QueryTagIndex),
                                        ("/queryhistory", QueryHistory)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
